package com.oto.web.resource;

import java.util.Collection;
import java.util.List;
import java.util.Set;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.oto.Constants;
import com.oto.model.FlowDO;
import com.oto.model.IndexDO;
import com.oto.service.FlowService;
import com.oto.service.PMF;
import com.oto.service.SearchService;

/**
 * @author xueqiang.mi
 * @since 2011-1-16
 */
@Path("/robot")
@Component
@Scope(BeanDefinition.SCOPE_SINGLETON)
public class RobotResource {
	@Autowired
	protected FlowService flowService;
	@Autowired
	protected SearchService searchService;

	@GET
	@Path("makeIndex/{number}")
	@Produces("text/plain")
	public String makeIndex(@PathParam("number") int number) {
		List<FlowDO> flows = flowService.latestUnsettled(number);
		for (FlowDO flow : flows) {
			Set<String> keys = searchService.parse(flow.getName());
			for (int i = 0; i < keys.size(); i++) {
				processKey(keys.toArray()[i].toString(), flow.getId());
			}
		}
		return Constants.STATUS_DONE;
	}

	private void processKey(String key, Long id) {
		PersistenceManager pm = PMF.get();
		try {
			Query query = pm.newQuery(IndexDO.class);
			query.setFilter("key == :key");

			@SuppressWarnings("unchecked")
			Collection<IndexDO> c = (Collection<IndexDO>) query.execute(key);
			IndexDO indexDO;
			if (c != null && !c.isEmpty()) {
				indexDO = (IndexDO) c.toArray()[0];
				indexDO.getFlows().add(id);
			} else {
				indexDO = new IndexDO();
				indexDO.setKey(key);
				indexDO.getFlows().add(id);
				pm.makePersistent(indexDO);
			}
		} finally {
			pm.close();
		}
	}
}
